package cn.it.dao.impl;

import cn.it.anno.MyAutowired;
import cn.it.anno.MyRepository;
import cn.it.dao.AccountDao;
import cn.it.pojo.Account;
import cn.it.utils.ConnectionUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MyRepository("AccountDao")
public class AccountDaoImpl implements AccountDao {

    @MyAutowired
    private ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    @Override
    public Account findById(String cardNo) throws SQLException {

        Connection connection = connectionUtils.getCurrentConn();
        PreparedStatement preparedStatement = connection.prepareStatement("select * from account where cardNo = ?");
        preparedStatement.setString(1,cardNo);
        ResultSet resultSet = preparedStatement.executeQuery();

        Account account = new Account();
        while (resultSet.next()){

            account.setCardNo(resultSet.getString("cardNo"));
            account.setName(resultSet.getString("name"));
            account.setMoney(resultSet.getDouble("money"));
        }

        return account;
    }

    @Override
    public void update(Account account) throws SQLException {

        Connection connection = connectionUtils.getCurrentConn();
        PreparedStatement preparedStatement = connection.prepareStatement("update account set money=? where cardNo = ?");
        preparedStatement.setDouble(1,account.getMoney());
        preparedStatement.setString(2,account.getCardNo());
        preparedStatement.executeUpdate();

    }


}
